package controller

import (
	"awesomeProject/lib"
	"github.com/gin-gonic/gin"
	"log"
)

// SetProfile 该函数暂时不提供密码修改
func SetProfile(c *gin.Context) {
	log.Println("setProfile running")
	var spReq lib.SetProfileReq
	if err := c.ShouldBindJSON(&spReq); err != nil {
		log.Println("read json fail in setProfile")
		c.JSON(400, lib.SetProfileResp{
			StatusCode: 0,
			StatusMsg:  "read json fail in server",
		})
		return
	}
	ok, err := AuthId(spReq.Id, spReq.Token)
	if err != nil {
		c.JSON(400, lib.SetProfileResp{
			StatusCode: 1,
			StatusMsg:  "id is wrong, please login again",
		})
		return
	}
	if !ok {
		c.JSON(400, lib.SetProfileResp{
			StatusCode: 1,
			StatusMsg:  "you don't have the right to do this",
		})
		return
	}
	newInfo := spReq.NewInfo
	if newInfo.Username == "" {
		newInfo.Username = "default_name"
	}
	if newInfo.Qq == "" {
		newInfo.Qq = "null"
	}
	if newInfo.Birthday == "" {
		newInfo.Birthday = "2003-08-13"
	}
	if newInfo.Email == "" {
		newInfo.Email = "null"
	}
	if newInfo.Photo == "" {
		newInfo.Photo = defaultPhoto
	}
	err = UpdateUserInfo(newInfo)
	if err != nil {
		log.Println("database update fail in setProfile", err)
		c.JSON(400, lib.SetProfileResp{
			StatusCode: 0,
			StatusMsg:  "database update fail",
		})
		return
	}
	c.JSON(400, lib.SetProfileResp{
		StatusCode: 2,
		StatusMsg:  "profile update successfully",
		NowInfo:    newInfo,
	})
	return
}

func UpdateUserInfo(u lib.User) error {
	stmt, err := pool.Prepare("update public.user set username=$1, photo=$2, gender=$3, email=$4, qq=$5, birthday=$6 where id=$7")
	if err != nil {
		log.Println("database fail in updateUserInfo")
		return err
	}
	_, err = stmt.Exec(u.Username, u.Photo, u.Gender, u.Email, u.Qq, u.Birthday, u.Id) //这里不用取地址?
	if err != nil {
		log.Println("statement exec fail in updateUserInfo")
		return err
	}
	return nil
}

func GetProfile(c *gin.Context) {
	var req lib.GetProfileReq
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Println("get json fail in getProfile")
		c.JSON(500, lib.GetProfileResp{
			StatusCode: 0,
			StatusMsg:  "get json fail",
		})
	}
	ok, err := AuthId(req.Id, req.Token)
	if err != nil {
		log.Println("auth fail in getProfile")
		return
	}
	if !ok {
		log.Println("token invalid in getProfile")
		return
	}
	user, ok, err := SearchId(req.Id)
	if !ok || err != nil {
		log.Println("search ID fail in getProfile")
		c.JSON(500, lib.GetProfileResp{
			StatusCode: 1,
			StatusMsg:  "ID invalid",
		})
		return
	}
	c.JSON(200, lib.GetProfileResp{
		StatusCode: 2,
		StatusMsg:  "getProfile successfully",
		User:       user,
	})
	return
}
